<?php
include_once "core.class.php";
include_once "coredb.class.php";
#include_once "../include/classes/loosediamonds.php";
#include_once "../include/classes/salesman.php";

global $core;


class Framework extends iFramework 
{
    function Framework()
    {
        iFramework::iFramework("framework",
                        array(
                            "plugins_folder" => CORE_BBPLUGINS_FOLDER,
                            "plugin_export_function_name" => "BBExport",
                            "default_plugin" => "staticpage",
                            "template_dir" => "/tpl",
                            "compile_dir" => "",
                            "config_dir" => "",
                            "cache_dir" => "",
                        ));
        $core = &getCoreInstance();
        $this->db = &new CoreDB($core->config["DB"]["dbtype"]."://".$core->config["DB"]["username"].":".$core->config["DB"]["password"]."@".$core->config["DB"]["hostspec"]."/".$core->config["DB"]["database"]);
        $this->db->initCache($core->config["DB"]['caching']);
        $core->setProperty("db", $this->db);


    }

    function doAction($arg = null)
    {
        if(null == $arg || !is_array($arg) || !count($arg))
        {
            $core = getCoreInstance();
                        $arg = array($this->default_plugin);
        }
                /// - --------------- from mail statistics (by Gendich)
                if (isset($_GET[frommail]))
                {
                        if (!isset($core)) $core = getCoreInstance();
                        $db = $core->getProperty("db");
                        list($user,$id)=explode("|", $_GET[frommail]);
                        if ($user == "subscribe") 
                        {$db->exec("update subscribe set mail_response_qty=mail_response_qty+1 where id=$id");}
                        if ($user == "client") 
                        {$db->exec("update clients set mail_response_qty=mail_response_qty+1 where client_id=$id");}
                }
                if (isset($_GET[mstat]))
                {
                        $db->exec("update mail_statistics set has_come=1 where id=$_GET[mstat]");
                        $_SESSION[mail_stat]=$_GET[mstat];   // 
                }
                /// - --------------- from mail statistics (by Gendich)
        $tag = $arg[0];
        if(isset($this->plugins[$tag]))
        {
            unset($arg[0]);
            $arg = ArrayReIndex($arg); //array_flip(array_flip($arg));
            return $this->plugins[$tag]->doAction($arg);
        }
        return false;
    }
    
    function checkImage($file, $folder, &$core, $default="")
    {
        if(file_exists($core->config["file_root"].$folder.$file))
        {
            return $folder.$file;
        }
        return $folder.$default;
    }


    function render($arg = null)
    {
       $core = getCoreInstance();
       $db = &$core->getProperty("db");
           
       $this->smarty->assign("page", $_GET["page"]);
       
        if(null == $arg || !is_array($arg) || !count($arg))
        {
            $arg = array($this->default_plugin);
        }
//      $menu = $this->CreateLeftMenu();
//      $this->smarty->assign("func_list", $menu);

        $this->smarty->assign("static_page", $this->default_plugin);
        $this->smarty->assign("staticpage_url", $core->getValues("staticpage_url"));
        $tag = $arg[0];
        $HTML = "
                <td colspan=\"3\" align=\"center\" valign=\"center\" id=\"content_text\" style=\"width: 100%; padding: 20px;\">
                
                <b>Sorry, no items found for your request.</b>
                
                </td>
                ";

                // --------<START> | Added by Gendich |  " LOGIN " -------------...
                 
         $this->smarty->assign("login", $this->getSessionCc());

                // --------<END>   | Added by Gendich | ---------------------------------------------///                   

                // --------<START> | Added by Gendich |  "  Assign right column "Sale Of The Day  "   -------------...
                $sotm_id = $db->getone("select `s_value` from settings where `s_key` like '%saleofthemonth%'");
                if($sotm_id > 0)
                {
                        $z = $db->getAll("select * from catalog where catalog_id=$sotm_id");
            //debug($z);
                        if(count($z)>0)
                        {
                                $z = $z[0];
                                $data = array(
                                                "pid" => $z["catalog_id"],
                                                "cid" => $z["parent_id"],
                                                "title" => $z["title"], );
                                // ---- check img [
                                        if (file_exists($core->config["file_root"]."/inventory/".$z[img_small]) && is_file($core->config["file_root"]."/inventory/".$z[img_small])) 
                                        {
                                                list($w_size,$h_size)=explode(',',$this->getimgsizes($core->config["file_root"],$z[img_small]));
                                                $default_w_size=90;
                                                $default_h_size=98;
                                                //debug($w_size,$h_size);
                                                $size="";
                                                if ($w_size>$h_size && $w_size>$default_w_size)
                                                        $size=" width=\"{$default_w_size}px\" ";
                                                if ($h_size>$w_size && $h_size>$default_h_size)
                                                $size=" height=\"{$default_h_size}px\" ";
                                                
                                                $data[img_small] = "<img $size src=\"inventory/".$z[img_small]."\" border=\"0\" >";
                                        } else 
                                        {
                                                $data[img_small] = "<img src='img/no_image.jpg' border=0 height=77/>";
                                        }
                                // ---- check img ]
                $this->smarty->assign("sotm", $data);
                        }
                }
                // --------<END>   | Added by Gendich | ---------------------------------------------///                   
                
                // ---------   right_banner [
                $link_id=$db->getone("select `s_value` from settings where `s_key` like '%right_banner%'");
                if ($link_id=="") $link_id="0";
                $this->smarty->assign("right_banner_id",  $link_id);
                // ---------   right_banner ]
                
        if(isset($this->plugins[$tag]))
        {
            unset($arg[0]);
            $arg = ArrayReIndex($arg);
            $HTML = $this->plugins[$tag]->Render($arg);
        }
        
        $core = &getCoreInstance();
        $db = &$core->getProperty("db");

        #SEO LINKS GENERATION START
                include_once(dirname(__FILE__)."/../lib/makeseolinks.php");
                makeseolinks($forall = false,$db);
        #SEO LINKS GENERATION END
        
        //... added by Gendich !
            $GLOBALS[db]=&$core->getProperty("db");;
        //... added by Gendich !
        $plugin = $core->getPathArguments();

        if(isset($this->plugins[$plugin[0]]))
        {
            $ppage = $this->plugins[$plugin[0]]->getProperty("MenuTitle");
        }
        else
        {
            if(isset($this->plugins[$this->default_plugin]))
            {
                $ppage = $this->plugins[$this->default_plugin]->getProperty("MenuTitle");
            }
            else
            {
                $ppage = "Unknown";
            }
        }

        $this->smarty->assign("parent_page", $ppage );

        if ($ppage == 'catalogpage'){
                
        

        } 


        $this->smarty->assign("err", $_GET["err"]);
        $this->smarty->assign("errtype", $_GET["errtype"]);
        

        // --------------------------------------------------------------------
        // --- Assign page HTML description, keywords and page title
        // --------------------------------------------------------------------

        $h_title        = $core->getProperty("h_title");
        $h_description  = $core->getProperty("h_description");
        $h_keywords     = $core->getProperty("h_keywords");
        $top_menu = $db->getAll("select *  from left_menu order by sibling asc");
        $this->smarty->assign("top_menu", ArrayDb2Str($top_menu));

        $_cart = $_SESSION['cart'];
               if(count($_cart)>0) {
                foreach($_cart as $k => $v)
                {
                //already done  $_cart[$k]['price'] = number_format($_cart[$k]['price'],2,'.',',');
                   // $value_warranty = $db->getOne("select warrantytype_price from products_warranty_types where warrantytype_id = {$_cart[$k][warranty]}");
                        
                        $_cart[$k]['price_nf'] = number_format($_cart[$k]['price'],2,'.',',');
                        $_cart[$k]['subtotal'] = ($_cart[$k]['price'] * $_cart[$k]['qty']);
                    $_cart[$k]['warranty'] = number_format($value_warranty * $_cart[$k]['qty'],2,'.',',');       
                        $_cart[$k]['subtotal'] = $_cart[$k]['subtotal'] - $_cart[$k]['discount'] + $_cart[$k]['warranty'];              
                        $_cart[$k]['discount'] = number_format($_cart[$k]['discount'],2,'.',',');               
                        $_cart[$k]['title'] = stripslashes($_cart[$k]['title']);
                    $_cart[$k][qty_on_stock]=$db->getone("select sum(qty) from store_history where catalog_id=$k");
                    $itogo += $_cart[$k]['subtotal'];
                    $qty += $_cart[$k]['qty'];
                }
               }
               
               
//        die(print_r($_cart));
                $itogo_nformat = number_format($itogo,2,'.',',');
        $this->smarty->assign("price", $itogo_nformat);
        $this->smarty->assign("qty", $qty);
        
        $this->smarty->assign("mega_http_root", $core->config["http_root"]);


//        $list_menu = $db->getall("select parent_id, catalog_id, title from catalog where parent_id != 0 and is_category = 'Y' and is_active = 'Y' order BY sibling asc LIMIT 10");
//        $this->smarty->assign("list_menu", $list_menu);
        $this->smarty->assign("h_title", ("" == $h_title) ? $db->getOne("select s_value from settings where `s_key` like '%h_title%'") : $h_title);
        $this->smarty->assign("h_description", ("" == $h_description) ? $db->getOne("select s_value from settings where `s_key` like '%h_description%'") : $h_description);
        $this->smarty->assign("h_keywords", ("" == $h_keywords) ? $db->getOne("select s_value from settings where `s_key` like '%h_keywords%'") : $h_keywords);

        if ( isset($_SESSION['xcount']) and $_SESSION['xcount'] != '') {
        $this->smarty->assign("xcount", $_SESSION['xcount']);
                                                                      }
        else {$this->smarty->assign("xcount", 0);}

        if ($_SESSION['xprice'] > 0) {
        $formated_price = number_format($_SESSION['xprice'],2,'.',',');
        $this->smarty->assign("xpricce", $formated_price);
                                     }
        else {$this->smarty->assign("xpricce", 0);}
            
        $catdata_id = $db->getone("select catalog_id from catalog where title like 'WATCHES%'");
        $this->smarty->assign("catdata_id", $catdata_id);

        // current page pressed button param
        $def_plugin = $this->default_plugin;
        //debug($def_plugin);

        $plugin = $core->getPathArguments();
        if(is_array($plugin) and count($plugin) == 0){
                $this->smarty->assign("plugin", '');
        }
        else{
                $this->smarty->assign("plugin", $plugin);
        }       

        $this->smarty->assign("content", $HTML);
        $this->smarty->assign("banner_temp", 'banner_temp.jpg');


        #$this->smarty->assign("client_id", $this->getSessionCc());

        #$x = $this->getallcd($this->getSessionCc(),$db);

        #$this->smarty->assign("client", $x);    

        $this->smarty->assign("prj_title", $core->config["system"]["prj_title"]);       


        if($core->config["DB"]['debug']){
                $db->showCache();
        }
                #ASSIGN SPECIALS BANNERS LINKS
       $this->smarty->assign("specials_categoryid1", $db->getone("select `s_value` from settings where `s_key` like '%right_banner1%'"));
       $this->smarty->assign("specials_categoryid2", $db->getone("select `s_value` from settings where `s_key` like '%right_banner2%'"));
       
        return $this->filterHTML($this->smarty->fetch("index.tpl.php"));

    }

    function getSessionCc(){
            return($_SESSION['cc']['client_id']);
    }

    function getallcd($client_id,&$db)                      { /* returns array(db from string) */
            $sql = "select * from clients where client_id='".str2db($client_id)."'";
            $r = $db->getrow($sql);
            $r = Arraydb2str($r);
            return $r;                      
    }

    function filterHTML($v){
        $v = preg_replace('(([a-zA-Z_0-9])(&)([a-zA-Z_0-9])(?![nbsp; || gt; || lt;]))','\\1'.'&amp;'.'\\3',$v);
        $v = preg_replace('(([ ])(&)([ ]))','\\1'.'&amp;'.'\\3',$v);
        $v = preg_replace('(([a-zA-Z_0-9])(&)(["]))','\\1'.'&amp;'.'\\3',$v);
        $v = str_replace('&st_','&amp;st_',$v);
        return trim($v);                                                                 
    }
                
        // ----------------------------------------------------------------------------------
        // --- [ GET IMAGES SIZE ] ----------------------------------------------------------
        // ----------------------------------------------------------------------------------

        function getimgsizes($froot,$img){ 
                if(isne($img) && is_file($froot.'/inventory/'.$img)) {
                        $img = $froot.'/inventory/'.$img;
                        $ar = getimagesize($img);
                        $arrr = $ar[0].','.($ar[1]+50);
                        return $arrr;
                }
                return "";
        } 

        
};

?>